package com.example.mgs.Service.Impl;

import com.example.mgs.Service.FileService;
import com.example.mgs.Service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.File;

@Service
@Slf4j
public class FileStorageServiceImpl implements FileStorageService {
    @Autowired
    private FileService fileService;

    // 临时文件清理定时器（每天凌晨清理超过24小时的临时文件）
    @Scheduled(cron = "0 0 0 * * ?")
    public void cleanupExpiredTempFiles() {
        try {
            File tempDir = new File(System.getProperty("user.dir") + "/temp/file-chunks/");
            if (!tempDir.exists() || !tempDir.isDirectory()) {
                return;
            }

            long now = System.currentTimeMillis();
            long expireTime = 24 * 60 * 60 * 1000; // 24小时

            File[] taskDirs = tempDir.listFiles();
            if (taskDirs != null) {
                for (File taskDir : taskDirs) {
                    if (taskDir.isDirectory()) {
                        // 如果目录存在超过24小时，删除
                        if (now - taskDir.lastModified() > expireTime) {
                            deleteDirectory(taskDir);
                            log.info("清理过期临时文件: {}", taskDir.getName());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("清理临时文件失败", e);
        }
    }

    private void deleteDirectory(File directory) {
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    file.delete();
                }
            }
        }
        directory.delete();
    }
}
